import Vue from 'vue'
import store from '@/store'
import VueRouter from 'vue-router'
import { loginCheck } from '@/api/common'
import { getToken } from '@/util/auth'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/home/index'),
    meta: {
    //   keepAlive: true, // true需要被缓存,false不需要
    //   requireAuth: true, // true需要登录,false不需要
      requireInfo: true // true需要用户信息,false不需要
    }
  },
  {
    path: '/search/:data',
    name: 'Search',
    component: () => import('../views/search/index')
  },
  {
    path: '/login',
    name: 'LoginPage',
    component: () => import('../views/login/LoginPage')
  },
  {
    path: '/register',
    name: 'RegisteredPage',
    component: () => import('../views/welcome-register/index.vue')
  },
  {
    path: '/push-order',
    name: 'PushOrder',
    component: () => import('../views/push-order/index')
  },
  {
    path: '/reset-password',
    name: 'PasswordPage',
    component: () => import('../views/retrieve-password/PasswordPage.vue')
  },
  {
    path: '/help-center',
    name: 'HelpCenter',
    component: () => import('../views/help-center/index.vue')
  },
  {
    path: '/my-order',
    name: 'MyOrder',
    component: () => import('../views/my-order/index.vue'),
    redirect() {
      return '/order'
    },
    children: [
      {
        path: '/order',
        name: 'Order',
        component: () => import('../views/order/index.vue')
      },
      {
        path: '/choose-for-him',
        name: 'ChooseForHim',
        component: () => import('../views/choose-for-him/index.vue')
      },
      {
        path: '/choose-for-mime',
        name: 'ChooseForMime',
        component: () => import('../views/choose-for-mime/index.vue')
      },
      {
        path: '/cart',
        name: 'Cart',
        component: () => import('../views/cart/index.vue')
      },
      {
        path: '/collect',
        name: 'Collect',
        component: () => import('../views/collect/index.vue')
      },
      {
        path: '/foot-mark',
        name: 'FootMark',
        component: () => import('../views/foot-mark/index.vue')
      },
      {
        path: '/my-rate',
        name: 'MyRate',
        component: () => import('../views/my-rate/index.vue')
      },
      {
        path: '/base-info-set',
        name: 'BaseInfoSet',
        component: () => import('../views/base-info-set/index.vue'),
        meta: {
          requireAuth: true,
          requireInfo: true
        }
      },
      {
        path: '/change-password',
        name: 'ChangePassword',
        component: () => import('../views/change-password/index.vue')
      },
      {
        path: '/deliver-address',
        name: 'DeliverAddress',
        component: () => import('../views/deliver-address/index.vue')
      },
      {
        path: '/message-center',
        name: 'MessageCenter',
        component: () => import('../views/message-center/index.vue'),
        meta: {
          requireAuth: true,
          requireInfo: true
        }
      },
      {
        path: '/primary-account',
        name: 'PrimaryAccount',
        component: () => import('../views/primary-account/index.vue')
      },
      {
        path: '/bypass-account',
        name: 'BypassAccount',
        component: () => import('../views/bypass-account/index.vue')
      },
      {
        path: '/regulatory-order',
        name: 'RegulatoryOrder',
        component: () => import('../views/regulatory-order/index.vue')
      },
      {
        path: '/regulatory-budget-orders',
        name: 'RegulatoryBudgetOrders',
        component: () => import('../views/regulatory-budget-orders/index.vue')
      }
    ]
  },
  {
    path: '/detail/:spuRepoId/:end', // 商品详情
    name: 'Detail',
    component: () => import('../views/detail/index')
  },
  {
    path: '/confirm-order',
    name: 'ConfirmOrder',
    component: () => import('../views/cart/ConfirmOrder.vue')
  },
  {
    path: '/scan-code',
    name: 'ScanCode',
    component: () => import('../views/cart/ScanCode.vue')
  },
  {
    path: '/prepaid', // 运费详情
    name: 'prepaid',
    component: () => import('../views/prepaid/index.vue')
  },
  {
    path: '/receiving-detail', // 订单详情-待收货
    name: 'ReceivingDetail',
    component: () => import('../views/order/ReceivingDetail')
  },
  {
    path: '/message-center-detail',
    name: 'MessageCenterDetail',
    component: () => import('../views/message-center/detail.vue')
  },
  {
    path: '/check-budget-orders', // 监管账号预算单-查看清单
    name: 'CheckBudgetOrders',
    component: () => import('../views/regulatory-budget-orders/check.vue')
  },
  {
    path: '/recruitment', // 商家入驻
    name: 'Recruitment',
    component: () => import('../views/recruitment/index.vue'),
    meta: {
      requireAuth: true,
      requireInfo: true
    }
  },
  {
    path: '/carriage-detail', // 运输详情
    name: 'CarriageDetail',
    component: () => import('../views/order/CarriageDetail.vue')
  },
  {
    path: '/appraise', // 评价
    name: 'Appraise',
    component: () => import('../views/order/Appraise.vue')
  },
  {
    path: '/menu-detail', // 选单详情
    name: 'MenuDetail',
    component: () => import('../views/choose-for-him/MenuDetail.vue')
  },
  {
    path: '/audit', // 公司信息
    name: 'audit',
    component: () => import('../views/corporate/audit.vue')
  },
  {
    path: '/corpMessage', // 待审核
    name: 'corpMessage',
    component: () => import('../views/corporate/corpMessage.vue')
  },
  {
    path: '/satisfaction', // 审核失败
    name: 'satisfaction',
    component: () => import('../views/corporate/satisfaction.vue')
  },
  {
    path: '/edit-orders', // 修改订单
    name: 'editOrders',
    component: () => import('../views/choose-for-mime/edit-orders.vue')
  },
  {
    path: '/information-list', // 资讯列表
    name: 'InformationList',
    component: () => import('../views/information/list.vue')
  },
  {
    path: '/information-detail', // 资讯详情
    name: 'InformationDetail',
    component: () => import('../views/information/detail.vue')
  },
  {
    path: '/bulletin-list', // 公告列表
    name: 'bulletin',
    component: () => import('../views/information/bulletin.vue')
  },
  {
    path: '/new-quence/:data', // 新搜索结果
    name: 'NewQuence',
    component: () => import('../views/search/NewQuence.vue')
  },
  {
    path: '/shop/:data', // 店铺列表
    name: 'Shop',
    component: () => import('../views/shop/index.vue')
  },
  {
    path: '/deal-snapshoot', // 交易快照
    name: 'DealSnapshoot',
    component: () => import('../views/order/SnapshootPage.vue')
  }
]

const router = new VueRouter({
  mode: 'history', // 去掉url中的锚/#/,使更像一个HTML网站,但是打包成App时,还是得用注释掉,使用router默认的hash模式
  routes
})
// 解决跳转重复路径代码报错代码
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (to.meta.requireAuth) {
      loginCheck().then(res => {
        if (res.data) {
          // 判断当前是否已拉取user_info信息
          if (to.meta.requireInfo && Object.keys(store.getters.info).length === 0) {
            // 拉取user_info
            store.dispatch('setInfo').then(() => {
              next({ ...to, replace: true })
            }).catch(() => {
              store.dispatch('FedLogOut').then(() => {
                next({ path: '/' })
              })
            })
          } else {
            next()
          }
        } else {
          store.dispatch('setToken', '')
          next({
            path: '/login',
            query: {
              redirect: to.fullPath
            }
          })
        }
      })
    } else if (to.meta.requireInfo && Object.keys(store.getters.info).length === 0) {
      loginCheck().then(res => {
        if (res.data) {
          // 拉取user_info
          store.dispatch('setInfo').then(() => {
            next({ ...to, replace: true })
          }).catch(() => {
            store.dispatch('FedLogOut').then(() => {
              next({ path: '/' })
            })
          })
        } else {
          next()
        }
      })
    } else {
      next()
    }
  } else {
    if (to.meta.requireAuth) {
      if (from.path.indexOf('login') !== -1) {
        next({
          path: '/'
        })
      } else {
        next({
          path: '/login',
          query: {
            redirect: to.fullPath
          }
        })
      }
    } else {
      next()
    }
  }
})

export default router
